<template>
  <div class="page-cont">
    <van-nav-bar
      title="问题列表"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div class="btn">
      <van-button
        type="info"
        size="small"
        @click="addQuestion"
        block
      >
        + 新增
      </van-button>
    </div>
    <van-tabs v-model="status">
      <van-tab
        title="质量问题"
        :name="1"
      />
      <van-tab
        title="安全问题"
        :name="2"
      />
    </van-tabs>
    <scroll-list
      v-model="list"
      @onLoad="onLoad"
      ref="list"
    >
      <question-item
        v-for="(item, i) in list"
        :key="i"
        :data="item"
        @remove="remove(i)"
        @close="close(i)"
        @edit="edit(i)"
      />
    </scroll-list>
  </div>
</template>

<script>
import ScrollList from '@/components/ScrollList/index.vue'
import QuestionItem from './components/QuestionItem.vue'

export default {
  name: "QuestionPage",
  components: {
    QuestionItem,
    ScrollList
  },
  data() {
    return {
      status: 1,
      list: [],
    };
  },
  created() {
  },
  watch: {
    status() {
      this.$refs.list.refresh()
    }
  },
  methods: {
    async onLoad(page, done) {
      let res = await this.api.GET_QUESTION_LIST({pageNo: page, pageSize: 10, type: this.status})
      this.list.push(...res.list)

      // 触发加载完成 大于50模拟全部加载完成
      done(res.pageNo === res.totalPage)
    },
    async remove(i) {
      let data = this.list[i]
      // 取消计划
      this.$dialog
        .confirm({
          title: "提示",
          message: "此操作将永久删除数据, 是否继续?",
        })
        .then(async () => {
          this.$toast.loading({message: "加载中...", forbidClick: true});
          await this.api.DELETE_QUESTION(data.id);
          this.$toast.clear();
          this.list.splice(i, 1)
          this.$forceUpdate()
        })
        .catch(() => {});
    },
    async close(i) {
      let data = JSON.parse(JSON.stringify(this.list[i]))
      data.status = 2
      this.$toast.loading({message: "加载中...", forbidClick: true});
      await this.api.EDIT_QUESTION(data);
      this.$toast.clear();
      this.$set(this.list[i], 'status', 2)
      this.$forceUpdate()
    },
    edit(i) {
      this.event.$once("edit_question_ok", (data) => {
        this.$set(this.list, i, data);
        this.$forceUpdate()
      });
      this.$router.push({
        path: "/question/edit",
        query: {
          json: JSON.stringify(this.list[i]),
        },
      });
    },
    addQuestion() {
      this.event.$once("add_question_ok", () => {
        this.$refs.list.refresh()
      });
      this.$router.push('/question/append')
    }
  }
};
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
